import axios from 'axios'
import { ElMessage, ElMessageBox  } from 'element-plus'
// import { useSideStore } from '@/store/state'
// import { getParams } from '@/utils/utils'
// const host = "http://118.178.95.225:8087/";
import { useRouter } from 'vue-router'
const router = useRouter()
const host = "/scoreapi";
import { getToken, setKeyItem} from '@/utils/auth'
const request = axios.create({
	// 此处的 '/api' 和 vite.config.js 的配置相关联
	baseURL: host,
	timeout: 60000,
})

// 数据请求拦截
request.interceptors.request.use(
	// 1. 返回config对象
	// 2. 可以设置携带 token 信息
	(config) => {
		const token = getToken() || "";
		return {
			...config,
			params: {
				...config.params,
				// key: getParams("key")
			},
			headers: {
				Authorization: token, // 请求头中携带token信息
				"Content-Type": config?.headers['Content-Type'] || "application/json",
				"Access-Control-Allow-Origin": "*",
			},
		};
	},
	(err) => {
		return Promise.reject(err)
	},
)

// 返回响应数据拦截
request.interceptors.response.use(
	(response) => {
		//   console.log("request.js打印返回信息" , response);
		// 简化返回数据

		if (response.data.codeId != 200) {
			ElMessage(response.data.codeDes)
			if (response.data.codeId == -99) {
				router.push({
					path: '/login'
				})
			}
			
			return Promise.reject(response.data)
			// return Promise.resolve(response.data)
		} else {
			return Promise.resolve(response.data)
		}
	},
	// 错误执行
	(error) => {
		console.log('错误信息', error)
		if (error.code === 'ECONNABORTED' && error.message.includes('timeout')) {
			ElMessage('提示系统繁忙，请稍后重试')
		} else if (error?.response?.status) {
			switch (error.response.status) {
				case 404:
					console.log('请求路径找不到！')
					break
				case 500:
					console.log('服务器内部报错！')
					break
				// 还可以自己添加其他状态码
				default:
					break
			}
		}
		return Promise.reject(new Error(error.message))
	},
)

// 暴露对象
export default request
